package com.tingyuge.base.thread.wang.chapter8;

/**
 * Created by xiaodao
 * date: 2019/11/29
 */
public class ThreadConsumerVersion1 {

    private int i  =0;
    private Object object = new Object();

    private   boolean isProduced = false;

    public void produce(){
        synchronized (object){
            while (isProduced){
                try {
                    object.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            i++;
            System.out.println("P->"+i);
            isProduced=true;
            object.notify();
        }

    }

    public void  consumer(){
        synchronized (object){
            while (!isProduced){
                try {
                    object.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            System.out.println("C->"+i);
            isProduced=false;
            object.notify();


        }
    }

    public static void main(String[] args) {
        ThreadConsumerVersion1 consumerVersion1 = new ThreadConsumerVersion1();
        new Thread(()->{
            while (true){
                try {
                    Thread.sleep(1000);
                    consumerVersion1.produce();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }).start();
        new Thread(()->{
            while (true){
                try {
                    Thread.sleep(1000);
                    consumerVersion1.consumer();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
